package com.czn.bookshop.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czn.bookshop.entity.Cart;
import com.czn.bookshop.entity.CartInfo;
import com.czn.bookshop.entity.CartVo;
import com.czn.bookshop.entity.User;
import com.czn.bookshop.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * 购物车控制器
 *
 * @author ChenZeNan
 * @create 2020-12-29 13:43
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    CartService cartService;

    /**
     * 添加到购物车
     *
     * @param cart
     * @param session
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public String add(Cart cart, HttpSession session) {
        User user = (User) session.getAttribute("user");
        cart.setUserId(user.getId());
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("book_Id", cart.getBookId());
        queryWrapper.eq("user_Id", user.getId());
        Cart queryCart = cartService.getOne(queryWrapper);
        if (queryCart == null) {
            cartService.save(cart);
        } else {
            queryCart.setCount(queryCart.getCount() + cart.getCount());
            cartService.updateById(queryCart);
        }
        return "success";
    }

    /**
     * 购物车列表
     *
     * @param httpSession
     * @param model
     * @return
     */
    @RequestMapping("/list")
    public String list(HttpSession httpSession, Model model) {

        User user = (User) httpSession.getAttribute("user");
        List<CartVo> cartVoList = cartService.findCartByUserId(user.getId());

        // 将购物车的记录数和总价格包装后放到session域中
        CartInfo cartInfo = cartService.wrapperCartInfo(cartVoList);
        httpSession.setAttribute("cartInfo", cartInfo);

        model.addAttribute("cartVoList", cartVoList);
        return "cart";
    }

    @RequestMapping("/update")
    @ResponseBody
    public String upate(Cart cart, HttpSession httpSession) {
        //更新
        cartService.updateById(cart);

        // 查询更新后的数据
        User user = (User) httpSession.getAttribute("user");
        List<CartVo> cartVoList = cartService.findCartByUserId(user.getId());

        // 将购物车的记录数和总价格包装后放到session域中
        CartInfo cartInfo = cartService.wrapperCartInfo(cartVoList);
        httpSession.setAttribute("cartInfo", cartInfo);

        double total = cartService.getCartItemTotal(cartVoList);
        return String.valueOf(total);
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(String ids) {
        return cartService.batchDelete(ids);
    }
}
